<template>
  <div class="patient-core">
	<dynamic-form ref="form" :value="innerValue" :options="[patientInfo]" @on-value-change="receiveValue"></dynamic-form>
	</div>
</template>

<script>
import patientInfo from "./patient-info";
//import hospitalization from "./hospitalization-info";
import dynamicForm from "lib/components/dynamic-form";
import { getValue, setValue } from "lib/components/dynamic-form/utils";
export default {
	props: {
		value: {
			type: [Object, Array]
		},
		clinicNumber: [Number, String]
	},
	components: {
		dynamicForm
	},
	data() {
		return {
			patientInfo,
			//hospitalization,
			patientInfoValue: {},
			ssss: [
				{
					formId: 1,
					values: [
						{
							_rowIndex: 0,
							name: {},
							clinicNumber: { data: "999" },
							birthday: {},
							phone: {},
							address: {},
							job: {},
							nation: { data: "汉" },
							sex: {},
							marriage: {}
						}
					]
				}
			]
		};
	},
	computed: {
		innerValue() {
			return this.value //如果有传入值，则直接回填
				? this.formateInput(this.value)
				: this.clinicNumber //如果有clinicNumber,则表示创建或者查看该clinicNumber的用户
					? this.formateInput({
							clinicNumber: this.clinicNumber
						})
					: this.formateInput();
		}
	},
	methods: {
		validate() {
			return this.$refs.form.validate();
		},
		//格式化传入值
		formateInput(vals) {
			console.log("vals", vals);
			if (!vals) {
				return;
			}
			console.log("vals", vals);
			let addre = ["province", "city", "area"];
			let res = {
				address: setValue({})
			};
			for (let i in vals) {
				if (addre.indexOf(i) > -1) {
					getValue(res.address)[i] = vals[i];
					continue;
				}
				res[i] = setValue(vals[i]);
			}
			console.log("res", [{ formId: 1, values: [res] }]);
			return [{ formId: 1, values: [res] }];
		},
		//格式化输出值的格式
		formateOutput(val) {
			let patientInfo = val.find(singleValue => singleValue.formId == 1)
				.values[0];
			let res = {};
			if (patientInfo) {
				for (let i in patientInfo) {
					if (i == "_rowIndex") continue;
					if (i == "address") {
						let address = getValue(patientInfo[i]);
						// let addressCopy = {};
						// for (let i in address) {
						// 	addressCopy[i] = JSON.stringify(address[i]); //&& address[i].value;
						// }
						res = {
							...res,
							...address
						};
					} else {
						res[i] = getValue(patientInfo[i]);
					}
				}
			}
			return res;
		},
		receiveValue(val) {
			console.log("receive", val);
			this.patientInfoValue = this.formateOutput(val);
			this.$emit("on-value-change", this.patientInfoValue);
		}
	},
	created() {
		// console.log("innerValue", JSON.stringify(this.innerValue));
		// console.log("inner", this.innerValue);
		//patientInfo
	}
};
</script>
